package com.yunpi.yunpicturebackend.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.yunpi.yunpicturebackend.config.CosClientConfig;
import com.yunpi.yunpicturebackend.exception.BusinessException;
import com.yunpi.yunpicturebackend.exception.ErrorCode;
import com.yunpi.yunpicturebackend.exception.ThrowUtils;
import com.yunpi.yunpicturebackend.manager.CosManager;
import com.yunpi.yunpicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
public abstract class PictureUploadTmplate {
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     * @param inputSource
     * @param uploadPathPrefix
     * @return
     */

    public UploadPictureResult uploadPicture(Object inputSource,String uploadPathPrefix){
        //1.校验图片
        voidPicture(inputSource);
        //2.图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = getOriginalFilename(inputSource);
        //拼接上传文件路径，而不是使用原始文件名称，可以增加安全性
        String uploadFilename =String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,
                FileUtil.getSuffix(originalFilename)
                );
        String uploadPath =String.format("/%s/%s",uploadPathPrefix,uploadFilename);
        //解析结果返回
        File file =null;
        try {
            //3.创建临时文件， 获取文件到服务信息
            file = File.createTempFile(uploadPath, null);
            //处理文件来源
            processFile(inputSource,file);
            //4.上传到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            //5.获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 获取到图片处理的结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (CollUtil.isNotEmpty(objectList)){
                //获取压缩之后得到的文件信息（获取规则处理的webp
                CIObject compressedCiObject = objectList.get(0);
                //缩略图默认是压缩后的原图
                CIObject thumbnailCiObject=compressedCiObject;
                //有生成缩略图，才获取缩略图
                if (objectList.size()>1){
                    //获取经过规则处理的缩略图
                    thumbnailCiObject = objectList.get(1);
                }

                //封装压缩之后的返回结果
                return buildResult(originalFilename,compressedCiObject,thumbnailCiObject);
            }

            return buildResult(originalFilename, uploadPath, file, imageInfo);
        } catch (Exception e) {
            log.error("图片文件上传失败"+e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
        }finally {
            //临时文件清除
            deleteTempFile(file);
        }

    }

    /**
     *封装返回结果
     * @param originalFilename
     * @param compressedCiObject
     * @param thumbnailCiObject 缩略图对象
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, CIObject compressedCiObject, CIObject thumbnailCiObject) {
        //计算算宽高
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

        //封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        //设置压缩后的原图地址
        uploadPictureResult.setUrl(cosClientConfig.getHost()+"/"+ compressedCiObject.getKey());
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        //设置缩略图地址
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost()+"/"+thumbnailCiObject.getKey());
        //返回可访问地址
        return uploadPictureResult;



    }

    /**
     *封装返回结果
     * @param originalFilename 原始文件名
     * @param compressedCiObject    压缩后的对象
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, CIObject compressedCiObject) {
        //计算算宽高
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

        //封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost()+"/"+ compressedCiObject.getKey());
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());

        //返回可访问地址
        return uploadPictureResult;

    }

    /**
     * 封装返回结果
     * @param originalFilename
     * @param uploadPath
     * @param file
     * @param imageInfo
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, String uploadPath, File file, ImageInfo imageInfo) {
        //计算算宽高
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

        //封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost()+"/"+ uploadPath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());

        //返回可访问地址
        return uploadPictureResult;
    }


    /**
     * 处理输入源并生成本地方法
     * @param inputSource
     */
    protected abstract void processFile(Object inputSource,File file) throws IOException;

    /**
     *获取输入源的原始文件名
     * @param inputSource
     * @return
     */

    protected abstract String getOriginalFilename(Object inputSource);
    /**
     * 检验输入源（本地文件或URL
     * @param inputSource
     */
    protected abstract void voidPicture(Object inputSource);


    public  void deleteTempFile(File file) {
        if (file !=null){
            //删除临时文件
            boolean deleteResult = file.delete();
            if (!deleteResult){
                log.error("file delete error ,filepath = {}",file.getAbsoluteFile());

            }
        }
    }





}
